package com.nbgs.demo.service.impl;

import com.nbgs.demo.controller.form.InsertConsumptionInfoForm;
import com.nbgs.demo.dao.InsertConsumptionInfoMapper;
import com.nbgs.demo.info.StageInfo;
import com.nbgs.demo.model.WaterBill;
import com.nbgs.demo.service.InsertConsumptionInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class InsertConsumptionInfoServiceImpl implements InsertConsumptionInfoService {


    @Autowired
    private InsertConsumptionInfoMapper insertConsumptionInfoMapper;

    @Override
    public void InsertConsumptionInfo(InsertConsumptionInfoForm insertInfo) {

        insertConsumptionInfoMapper.insertConsumptionInfo(insertInfo);

        double consumptionVolume = insertInfo.getConsumptionEnd()- insertInfo.getConsumptionStart();
        if(consumptionVolume>0){
            //根据用水性质来判断来找出所有阶段
            //用来记录上一次的水量最大边界值（梯度计算）
            Double preScope = 0.0;
            //用来记录算出来的水费
            Double payable = 0.0;
            //用一个hashMap集合来存储水量范围id以及水量上线范围
            List<StageInfo> waterScopeInfo = insertConsumptionInfoMapper.selectAllScopeInfo(insertInfo.getType());
            //用来标记使用量是否大于第一阶段,若大于，就先变为false,方便最后阶梯计价；否则就直接进行查询当前范围id对应的价格计算

            log.info("返回的数据："+waterScopeInfo.toString());

            boolean bool = true;
            for ( StageInfo waterInfo: waterScopeInfo) {
                //根据遍历的用水范围id去找到对应水价格
                double price = insertConsumptionInfoMapper.selectCurrentScopeWaterPrice(waterInfo.getStageId());

                if (waterInfo.getStageScope()< consumptionVolume) {
                    payable += (waterInfo.getStageScope() - preScope) * price;
                    preScope = waterInfo.getStageScope();
                    bool =false;
                } else {
                    if(bool){
                        payable+=consumptionVolume*price;
                    }else{
                        payable+=(consumptionVolume-preScope)*price;

                    }
                    break;
                }
            }
            WaterBill waterBill = new WaterBill();
            waterBill.setCardId(insertConsumptionInfoMapper.selectCardId(insertInfo.getCardNum()));
            waterBill.setConsumptionVolume(consumptionVolume);
            waterBill.setPayable(payable);
            waterBill.setBillGenerateTime(new Timestamp(System.currentTimeMillis()));
            waterBill.setConsumptionId(insertInfo.getConsumptionId());

            insertConsumptionInfoMapper.insertInfo(waterBill);
        }

    }
}
